
import getUserTempId from "@/util/userTempid";
import { requestLogin, requestUserInfo, requestLogout } from '@/api';
const state = {
  userTempId: getUserTempId(),
  //取本地区token
  token: localStorage.getItem("user_Token") || "",
  nickName: ""
};
const mutations = {
  SET_TOKEN_STATE(state, value) {
    state.token = value
  },
  SET_USERNAME_STATE(state, value) {
    state.nickName = value
  },
  SET_LOGOUT_STATE(state) {
    state.token = "";
    state.nickName = "";
    //移除本地token
    localStorage.removeItem("user_Token");
  },
};
const actions = {
  // requestUserInfo
  async getLogin({ commit }, userInfo) {
    const result = await requestLogin(userInfo)
    // console.log(result, "result");
    commit("SET_TOKEN_STATE", result.token)
    //请求到token之后,要把token持久化到本地中,否则刷新以后vuex就没有数据了,用户需要重新登录
    localStorage.setItem("user_Token", result.token);
  },
  async getUserName({ commit }) {
    // const result = await requestUserInfo()
    // commit("SET_USERNAME_STATE", result.nickName)
    try {
      const result = await requestUserInfo();
      console.log(result);
      commit("SET_USERNAME_STATE", result.nickName);
    } catch (e) {
      //在使用token发送请求的时候,如果token过期,则会抛出错误,被这里接受,我们可以清除掉token
      localStorage.removeItem("user_Token");
      //如果这里请求报错,则返回一个失败的promise实例,则dispatch方法就会返回这个失败的实例
      return Promise.reject();
    }
  },
  //退出登录
  async getLogout({ commit }) {
    await requestLogout();
    commit("SET_LOGOUT_STATE");
  },

};
const getters = {

};
export default {
  // 可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后，它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
